﻿using System;
using System.IO;
using System.Text;
using System.Web;
using System.Net;
using System.Web.Security;
using ActionModel.WebModel;
using ActionModel.Utility;
using System.Web.UI.WebControls;
using System.Linq;
using FilesArranger;
using System.Collections.Generic;

public partial class FileTree : PageBase
{

	protected void Page_Load(object sender, EventArgs e)
	{
	}

	protected override void OnHttpGET()
	{
		//if (Session["logined"] == null) Session["logined"] = false;
		string RequestAction = Request.QueryString["act"];
		switch (RequestAction)
		{
			#region 下载文件
			case "download":
				{
					string path = Server.HtmlDecode(Request.QueryString["path"]);
					if (path != null && path != "")
					{
						string PhysicalPath = MapPath(path);
						bool IsFirefox = (Request.QueryString["IsFirefox"] == "on" ? true : (Request.UserAgent.IndexOf("Firefox") != -1));
						OutPutFile(PhysicalPath, IsFirefox);
					}
					Response.End();
				}
				break;
			case "remotedownload":
				{
					string remoteUrl = Request.QueryString["url"];
					OutPutRemoteFile(remoteUrl);
					Response.End();
				}
				break;
			#endregion
		}
		base.OnHttpGET();
	}

	/// <summary>
	/// 远程文件下载
	/// </summary>
	/// <param name="FilePath">文件路径</param>
	/// <returns></returns>
	internal bool OutPutRemoteFile(string RemoteUrl)
	{
		if (Request.UserAgent.IndexOf("Firefox") != -1)
		{
			RemoteUrl = RemoteUrl + (RemoteUrl.IndexOf('?') == -1 ? "?" : "&") + "IsFirefox=on";
		}
		Stream responseStream = null;

		try
		{
			HttpWebRequest request = (HttpWebRequest)WebRequest.Create(RemoteUrl);
			long startPosition = 0L;
			string range = Request.Headers["Range"];
			if (range != null)
			{
				Response.StatusCode = 0xce;
				string str2 = base.Request.Headers["Range"].Replace("bytes=", "");
				startPosition = long.Parse(str2.Substring(0, str2.IndexOf("-")));
				request.AddRange((int)startPosition);
			}
			HttpWebResponse response = (HttpWebResponse)request.GetResponse();
			if (startPosition != 0L)
			{
				if (response.Headers["Content-Range"] != null)
				{
					Response.AddHeader("Content-Range", response.Headers["Content-Range"]);
				}
				else
				{
					Response.Write("源站点不支持断点下载");
					Response.End();
				}
			}
			Response.ContentType = "application/octet-stream;charset=UTF-8";
			if (response.Headers["Content-Length"] != null)
			{
				Response.AppendHeader("Content-Length", response.Headers["Content-Length"]);
			}
			if (response.Headers["Content-Disposition"] != null)
			{
				Response.AppendHeader("Content-Disposition", response.Headers["Content-Disposition"] + ".___");
			}
			else
			{
				string filename = RemoteUrl.Substring(RemoteUrl.LastIndexOf('/')) + ".___";
				Response.AppendHeader("Content-Disposition", "attachment; filename" + (Request.UserAgent.IndexOf("Firefox") != -1 ? "*" : "") + "=" + HttpUtility.UrlEncode(filename).Replace("+", "%20"));
			}
			long length = response.ContentLength;

			//HttpStatusCode code = response.StatusCode;

			responseStream = response.GetResponseStream();
			byte[] buffer0 = new byte[0x2800];
			while (length > 0)
			{
				if (Response.IsClientConnected)
				{
					int count = responseStream.Read(buffer0, 0, 0x2800);
					Response.OutputStream.Write(buffer0, 0, count);
					Response.Flush();
					buffer0 = new byte[0x2800];
					length -= count;
				}
				else
				{
					length = -1L;
				}
			}
			return true;
		}
		catch (Exception exception)
		{
			Response.Write("下载错误：<br/>");
			Response.Write("地址：" + Server.HtmlEncode(RemoteUrl) + "<br/>");
			Response.Write("原因：" + exception.Message);
			return false;
		}
		finally
		{
			if (responseStream != null)
			{
				responseStream.Close();
			}
		}
	}

	void putFiles(string path)
	{
		try
		{
			string PhysicalPath = MapPath(path);
			DirectoryInfo theFolder = new DirectoryInfo(PhysicalPath);
			if (theFolder.Exists)
			{
				//foreach (FileInfo nextFile in theFolder.GetFiles())
				//{
				//    Response.Write(nextFile.FullName.Substring(sub).Replace('\\', '/') + "|" + nextFile.Name + "|" + nextFile.Extension + "?");
				//}

				int preLength = MapPath("/").Length - 1;
				FileInfo[] files = theFolder.GetFiles();
				TreeNode[] nodes = files.Select(f => new TreeNode()
				{
					Text = f.Name,
					Value = f.FullName.Substring(preLength).Replace('\\', '/'),
					ImageUrl = f.Extension,
					ToolTip = f.Length.ToString(),
					ImageToolTip = f.LastWriteTime.ToLongTimeString()

				}).ToArray();
				JsonResult.WriteSuccess(nodes);

			}
		}
		catch (Exception ex)
		{
			Response.StatusCode = 500;
			Response.Write(ex.Message);
			Response.End();
		}
	}

	/// <summary>
	/// 文件下载流
	/// </summary>
	/// <param name="FilePath">文件路径</param>
	/// <returns></returns>
	internal bool OutPutFile(string FilePath, bool IsFirefox)
	{
		Stream stream = null;
		bool flag;
		byte[] buffer = new byte[0x2800];
		string fileName = Path.GetFileName(FilePath);
		try
		{
			stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
			long length = stream.Length;
			long startPosition = 0L;
			if (Request.Headers["Range"] != null)
			{
				Response.StatusCode = 0xce;
				string str2 = base.Request.Headers["Range"].Replace("bytes=", "");
				startPosition = long.Parse(str2.Substring(0, str2.IndexOf("-")));
			}
			if (startPosition != 0L)
			{
				string[] strArray = new string[] { "bytes ", startPosition.ToString(), "-", (length - 1L).ToString(), "/", length.ToString() };
				Response.AddHeader("Content-Range", string.Concat(strArray));
			}
			long leftBytes = length - startPosition;
			Response.AddHeader("Content-Length", leftBytes.ToString());
			Response.ContentType = "application/octet-stream;charset=UTF-8";
			Response.AddHeader("Content-Disposition", "attachment; filename" + (IsFirefox ? "*" : "") + "=" + HttpUtility.UrlEncode(fileName).Replace("+", "%20"));
			stream.Position = startPosition;
			length -= startPosition;
			while (length > 0L)
			{
				if (Response.IsClientConnected)
				{
					int count = stream.Read(buffer, 0, 0x2800);
					Response.OutputStream.Write(buffer, 0, count);
					Response.Flush();
					buffer = new byte[0x2800];
					length -= count;
				}
				else
				{
					length = -1L;
				}
			}
			flag = true;
		}
		catch (Exception exception)
		{
			Response.Write(exception.Message);
			flag = false;
		}
		finally
		{
			if (stream != null)
			{
				stream.Close();
			}
		}
		return flag;
	}



}
